<script setup>
import {
  queryPageApi,
  queryByIdApi,
  addApi,
  updateApi,
  deleteApi,
  queryDeptListApi,
  queryRoleListApi,
  uploadApi,
} from "@/api/user";
import { ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

onMounted(() => {
  // 页面加载完成后获取部门列表、角色列表和用户数据
  getDeptList();
  getRoleList();
  search();
});

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const total = ref(0);
const deptList = ref([]); // 部门列表
const roleList = ref([]); // 角色列表
const selectedRows = ref([]); // 选中的行数据

// 对话框相关
const formtitle = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";
const user = ref({
  username: "",
  password: "",
  name: "",
  phone: "",
  email: "",
  gender: "", // 改为空值，显示"请选择"
  status: "", // 改为空值，显示"请选择"
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});

// 表单校验规则
const userFormRef = ref(null);
const rules = ref({
  username: [
    { required: true, message: "用户名为必填项", trigger: "blur" },
    { min: 2, max: 20, message: "用户名应该在2-20位之间", trigger: "blur" },
  ],
  name: [
    { required: true, message: "姓名为必填项", trigger: "blur" },
    { min: 2, max: 20, message: "姓名应该在2-20位之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号为必填项", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱为必填项", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  gender: [{ required: true, message: "性别为必填项", trigger: "change" }],
  status: [{ required: true, message: "状态为必填项", trigger: "change" }],
});

// 获取部门列表
const getDeptList = async () => {
  try {
    const result = await queryDeptListApi();
    if (result.code === 1) {
      deptList.value = result.data;
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
  }
};

// 获取角色列表
const getRoleList = async () => {
  try {
    const result = await queryRoleListApi();
    if (result.code === 1) {
      roleList.value = result.data;
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 搜索用户
const search = async () => {
  try {
    const result = await queryPageApi(queryParams.value);
    if (result.code === 1) {
      userList.value = result.data.rows;
      total.value = result.data.total;
    } else {
      ElMessage.error(result.msg || "查询失败");
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败，请重试");
  }
};

// 清空搜索条件
const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  queryParams.value.page = 1;
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val;
  search();
};

// 选择变更处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 添加用户
const handleAdd = () => {
  dialogFormVisible.value = true;
  formtitle.value = "新增用户";
  user.value = {
    username: "",
    password: "",
    name: "",
    phone: "",
    email: "",
    gender: "", // 改为空值
    status: "", // 改为空值
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.clearValidate();
    }
  });
};

// 编辑用户
const handleEdit = async (id) => {
  try {
    const result = await queryByIdApi(id);
    if (result.code === 1) {
      dialogFormVisible.value = true;
      formtitle.value = "修改用户";
      user.value = { ...result.data };
      nextTick(() => {
        if (userFormRef.value) {
          userFormRef.value.clearValidate();
        }
      });
    } else {
      ElMessage.error(result.msg || "获取用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败，请重试");
  }
};

// 保存用户
const save = async () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result;
        if (user.value.id) {
          // 编辑
          result = await updateApi(user.value);
        } else {
          // 新增 - 设置默认密码
          user.value.password = user.value.username + "123";
          result = await addApi(user.value);
        }

        if (result.code === 1) {
          ElMessage.success("保存成功");
          dialogFormVisible.value = false;
          search(); // 重新加载数据
        } else {
          ElMessage.error(result.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败，请重试");
      }
    }
  });
};

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const result = await deleteApi(id);
    if (result.code === 1) {
      ElMessage.success("删除成功");
      search(); // 重新加载数据
    } else {
      ElMessage.error(result.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

// 批量删除用户
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  try {
    const names = selectedRows.value.map((row) => row.name).join("、");
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个用户吗？\n${names}`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.value.map((row) => row.id).join(",");
    const result = await deleteApi(ids);

    if (result.code === 1) {
      ElMessage.success("批量删除成功");
      selectedRows.value = []; // 清空选择
      search(); // 重新加载数据
    } else {
      ElMessage.error(result.msg || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败，请重试");
    }
  }
};

// 头像上传处理
const handleAvatarUpload = async (file) => {
  try {
    const result = await uploadApi(file);
    if (result.code === 1) {
      user.value.image = result.data;
      ElMessage.success("头像上传成功");
    } else {
      ElMessage.error(result.msg || "头像上传失败");
    }
  } catch (error) {
    console.error("头像上传失败:", error);
    ElMessage.error("头像上传失败，请重试");
  }
};

// 格式化状态显示
const formatStatus = (status) => {
  return status === 1 ? "正常" : "停用";
};

// 弹窗关闭处理
const handleDialogClose = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 150px"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="clear">
          <el-icon><Refresh /></el-icon>清空
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column prop="name" label="姓名" width="120" align="center" />

      <el-table-column
        prop="username"
        label="用户名"
        width="180"
        align="center"
      />

      <el-table-column label="头像" width="130" align="center">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.image" :alt="scope.row.name" />
        </template>
      </el-table-column>

      <el-table-column
        prop="deptName"
        label="部门"
        width="150"
        align="center"
      />

      <el-table-column
        prop="roleName"
        label="角色"
        width="170"
        align="center"
      />

      <el-table-column prop="phone" label="手机号" width="180" align="center" />

      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="220"
        align="center"
      />

      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="formtitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        :model="user"
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
        class="user-form"
      >
        <!-- 第一行：用户名和姓名 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="user.username"
                placeholder="请输入用户名"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="user.name"
                placeholder="请输入姓名"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：手机号和邮箱 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="user.phone"
                placeholder="请输入手机号"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="user.email"
                placeholder="请输入邮箱"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：性别和状态 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="user.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="user.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：部门和角色 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门">
              <el-select
                v-model="user.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select
                v-model="user.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 头像上传区域 -->
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="handleAvatarUpload"
            accept=".png,.jpg,.jpeg"
          >
            <img v-if="user.image" :src="user.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            图片上传,支持扩展名: .png/.jpg/.jpeg 大小限制: 2M
          </div>
        </el-form-item>

        <!-- 备注说明区域 -->
        <el-form-item label="备注说明">
          <el-input
            v-model="user.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多200字"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  margin-bottom: 16px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式优化 */
:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 头像上传样式 */
.avatar-uploader {
  text-align: center;
  /* 实体边框 */
  border: 1px solid #525050;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 搜索表单响应式 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-buttons {
    margin-left: 0 !important;
    margin-top: 16px;
  }
}
</style>
